//
//  TimeHandler.swift
//  HeadlineNews
//
//  Created by han on 2019/7/19.
//  Copyright © 2019 han. All rights reserved.
//

import Foundation

struct TimeHandler {
    
    struct SecondsTime {
        static let minute = 60
        static let hour = 60 * 60
        static let day = 12 * 60 * 60
    }
    
    static let normalFormat = "yyyy-MM-dd HH:mm:ss"
    
    // MARK: 计算日期
    // 是否是今天
    static func isDateInToday(date: Date) -> Bool {
        
        return NSCalendar.current.isDateInToday(date)
    }
    
    // 是否是今年
    static func isDateInThisYear(date: Date) -> Bool {
        
        let calendar = NSCalendar.current
        let selfDate = calendar.dateComponents([.year], from: date)
        let nowDate = calendar.dateComponents([.year], from: Date())
        return selfDate == nowDate
    }
    
    // 是否在一年内
    static func isDateInOneYear(date: Date) -> Bool {
        
        let calendar = NSCalendar.current
        let year = calendar.component(.year, from: date)
        if year < 1 { // 一年内
            return true
        }
        return false
    }
    
    // MARK: 计算时间
    
    /**
     1. Date() 获取到的时间为GMT时间
     2. 当用DateFormatter转化为字符串时，会自动根据时区转化。将date转化为当前时区时间。
     3. 时间戳是以GTM时区为标准的。
     4. 当格式字符串和时间戳互相转换时，DateFormatter会自动根据当地时区转换，相应的+8或-8
     
     */
    
    /// 时间转换为字符串
    static func timeString(date: Date? = Date(), timeFormat: String = TimeHandler.normalFormat) -> String? {
        guard let date = date else { return nil }
        let formater = TimeHandler.dateFormatter(timeFormat)
        return formater.string(from: date)
    }
    
    /// 时间戳转时间字符串
    static func timeString(timestamp: String, timeFormat: String = TimeHandler.normalFormat) -> String? {
        
        guard let interval = Double(timestamp) else { return nil }
        
        let date = Date(timeIntervalSince1970: interval)
        let formater = TimeHandler.dateFormatter(timeFormat)
        return formater.string(from: date)
    }
    
    /// 获取时间戳
    static func timestamp(date: Date? = Date()) -> String? {
        guard let date = date else { return nil }
        let interval = date.timeIntervalSince1970
        return String(format: "%.f", interval)
    }
    
    /// 获取时间戳
    static func timestampMilli(date: Date? = Date()) -> String? {
        guard let date = date else { return nil }
        let interval = date.timeIntervalSince1970
        let target: UInt64 = UInt64(interval * 1000)
        return String(format: "%llu", target)
    }
    
    /// 字符串转时间戳
    static func timestamp(timeString: String?, timeFormat: String = TimeHandler.normalFormat) -> String? {
        
        // 输入的字符串为当前时区的时间
        guard let timeString = timeString else { return nil }
        
        let formater = TimeHandler.dateFormatter(timeFormat)
        let date = formater.date(from: timeString)
        let interval = date?.timeIntervalSince1970
        guard interval != nil else { return nil }
        return String(format: "%.f", interval!)
    }
    
    /// 计算时间间隔 from - to
    static func timeInterval(from: String?, to: String?, timeFormat: String = TimeHandler.normalFormat) -> TimeInterval? {
        guard let to = to else { return nil }
        
        let formater = TimeHandler.dateFormatter(timeFormat)
        let toDate = formater.date(from: to)
        
        guard let from = from else { return timeInterval(toDate: toDate) }
        
        let fromDate = formater.date(from: from)
        return timeInterval(fromDate: fromDate, toDate: toDate)
    }
    
    /// 计算时间间隔 fromDate - toDate
    static func timeInterval(fromDate: Date? = Date(), toDate: Date?) -> TimeInterval? {
        guard let fromDate = fromDate, let toDate = toDate else { return nil }
        
        // 将两个比较时间都加上当地时区的时间间隔
        let timeZone = TimeZone.current
        let from = fromDate.addingTimeInterval(Double(timeZone.secondsFromGMT(for: fromDate)))
        let to = toDate.addingTimeInterval(Double(timeZone.secondsFromGMT(for: toDate)))
        // ReferenceDate 以2001/01/01 GMT为时间基础，计算时间间隔
        let interval = from.timeIntervalSinceReferenceDate - to.timeIntervalSinceReferenceDate
        return  interval
    }
    
    /// 描述时间间隔
    static func descriptionInterval(_ interval: TimeInterval?) -> String {
        guard let interval = interval else { return "" }
        let minutes = interval / 60;
        let hours = interval / 60 / 60;
        let day = interval / 60 / 60 / 24;
        let month = interval / 60 / 60 / 24 / 30;
        let years = interval / 60 / 60 / 24 / 365;
        
        var description = ""
        if minutes <= 1 {
            description = "刚刚"
        } else if (minutes < 60) {
            
            description = String(format: "%.f分钟前", floor(minutes))
        } else if (hours < 24) {
            description = String(format: "%.f小时前", floor(hours))
        } else if (day < 30) {
            description = String(format: "%.f天前", floor(day))
        } else if (month < 12) {
            description = String(format: "%.f个月前", floor(month))
        } else if (years > 1) { // 一年前
            return ""
        }
        return description
    }
    
    
    
    /// 默认会将Date转化为当前时区显示
    static private func dateFormatter(_ timeFormat: String = "yyyy-MM-dd HH:mm:ss") -> DateFormatter {
        let formater = DateFormatter()
        // 默认需要转化的Date为GTM时区数据，然后转化为当前时区数据
        formater.locale = Locale.current
        //Locale.init(identifier: "zh_CN")
        //        formater.dateStyle = .medium // 日期设置格式
        //        formater.timeStyle = .short // 时间设置格式
        // 按照自定义设置格式
        formater.dateFormat = timeFormat
        return formater
    }
    
    /// 传入的Date已经是当前时区的日期时间
    static private func dateFormatterWithoutTrans(_ timeFormat: String = "yyyy-MM-dd HH:mm:ss") -> DateFormatter {
        let formater = DateFormatter()
        // 设置时区为GMT，这样获取到的结果就不会转换为当前时区。
        let timeZone = TimeZone(secondsFromGMT: 0)
        formater.timeZone = timeZone
        formater.dateFormat = timeFormat
        return formater
    }
    
    
    /** usage:
     
     // 1562048648 2019-07-02 14:24:08
     print(Date(timeIntervalSince1970: 1562048648)) // 2019-07-02 06:24:08 +0000 GTM时区时间
     print(TimeHandler.timeString(timestamp: "1562048648") ?? "0") // 2019-07-02 14:24:08 当地时区时间（北京）
     print("时间戳 " + (TimeHandler.timestamp(timeString: "2019-07-02 14:24:08") ?? "0")) // 1562048648
     
     let interval = TimeHandler.timeInterval(from: nil, to: "2019-07-02 14:24:08")
     print("\(interval) + \(TimeHandler.descriptionInterval(interval))")
     
     */
    
    
}



